package cn.dglydrpy.eshop.website.learn;

import io.micrometer.core.instrument.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * 自定义监控
 */
@Endpoint(id="my")
@Component
public class MyEndPoint {

    //监控注册器  springboot自带,直接注入即可
    private MeterRegistry meterRegistry;

    private Counter counter;

    public MeterRegistry getMeterRegistry() {
        return meterRegistry;
    }
    @Autowired
    public void setMeterRegistry(MeterRegistry meterRegistry) {
        this.meterRegistry = meterRegistry;
        counter = Counter.builder("requestConter").description("请求计数").register(meterRegistry);//注册
    }

    @ReadOperation
    public String endPoint(){
        //修改监控数据
        counter.increment();  //原子性的++
        //Iterable<Measurement> measure = counter.measure();
        return counter.count()+"";
    }
    @ReadOperation
    public Map<Statistic, Double> endPoint2(){
        //拿监控数据
        Meter meter = meterRegistry.find("jvm.threads.live").meter();
        Map<Statistic,Double> map = StreamSupport.stream(meter.measure().spliterator(),false)
                .collect(Collectors.toMap(Measurement::getStatistic,Measurement::getValue));
        return map;
    }
}

